import {Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {FormBase} from './form-base';
import {ConfigService} from '@kylin/config';
import {HttpService} from '@kylin/http';
import {FormControlService} from './form-control.service';


@Component({
    selector: 'kylin-dynamic-form-base',
    templateUrl: './dynamic-form-base.component.html',
    styleUrls: ['./dynamic-form-base.component.less'],
    providers: [FormControlService]
})
export class DynamicFormBaseComponent implements OnInit, OnChanges {

    @Input() formBase: FormBase<any>;
    @Input() form: FormGroup;
    @Output() valueChange: EventEmitter<{ value: any }> = new EventEmitter<{ value: any }>();
    nzSmLabel: number;
    nzSmControl: number;
    hasLabel: boolean; // 是否需要label
    needLabelControlType: string[] = ['hidden', 'title', 'upload', 'location'];

    constructor(private msg: NzMessageService,
                private configService: ConfigService,
                private http: HttpService,
                private fcs: FormControlService) {
    }

    ngOnChanges(changes: SimpleChanges): void {
        if (changes.formBase) {
            this.hasLabel = this.needLabelControlType.indexOf(this.formBase.controlType) !== -1;
        }
    }

    ngOnInit() {
        switch (this.formBase.length) {
            case 24:
                this.nzSmLabel = 6;
                this.nzSmControl = 18;
                break;
            default:
                this.nzSmLabel = 12;
                this.nzSmControl = 12;
        }
        switch (this.formBase.controlType) {
            case 'upload':
                break;
            case 'select':
                if (this.formBase['init'] && this.formBase['fetchData']) {
                    this.selectOptionsInit();
                }
                if (this.formBase['multiple']) {

                }
                break;
        }
    }

    private selectOptionsInit() {
        this.fcs.fetchSelectOptions(this.formBase['fetchData']['path'], this.formBase['fetchData'])
            .then((res) => {
                this.formBase['options'] = res;
            });
    }

    selectValueChange(selectValue) {
        this.valueChange.emit({value: selectValue});
    }
}
